﻿using DBManager.Model;
using DBManager.UserCode;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DBManager
{
    public partial class Restore : Form
    {
        public Restore(string serverName, string userName, string userPwd)
        {
            InitializeComponent();
            this.Icon = MyResource.icon;
            this.serverName = serverName;
            this.userName = userName;
            this.userPwd = userPwd;
            gvFileList.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//设置为整行被选中
        }

        private string serverName { get; set; }

        private string userName { get; set; }

        private string userPwd { get; set; }

        /// <summary>
        /// 获取连接字符串
        /// </summary>
        /// <param name="dbName"></param>
        /// <returns></returns>
        public string GetConnStr(string dbName = "master")
        {
            return SqlCommon.GetConnStr(serverName, userName, userPwd, dbName);
        }

        private void Restore_Load(object sender, EventArgs e)
        {
            DataTable dt = SqlCommon.GetDataBase(GetConnStr());
            if (dt != null)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    clbDbList.Items.Add(dr["name"]);
                }
            }
        }

        private void clbDbList_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            //取消选中就不用进行以下操作  
            if (e.CurrentValue == CheckState.Checked)
            {
                gvFileList.DataSource = null;
                return;
            }
            for (int i = 0; i < ((CheckedListBox)sender).Items.Count; i++)
            {
                ((CheckedListBox)sender).SetItemChecked(i, false);
            }
            e.NewValue = CheckState.Checked;
            //可查看本机及远程服务器备份文件名
            DataTable dt = SqlCommon.GetBackupList(GetConnStr(), clbDbList.Text);
            gvFileList.DataSource = dt;
            gvFileList.Columns[0].HeaderCell.Value = "历史备份文件名";
            gvFileList.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;

            //只可查看本机备份的文件
            //List<FileInfoModel> fileList = FileCommon.GetFileInfoList(FileCommon.backupPath, "*" + clbDbList.Text + "*.bak");
            //gvFileList.DataSource = fileList.OrderByDescending(f => f.CreateTime).ToList();
            //gvFileList.Columns[0].HeaderCell.Value = "备份文件名";
            //gvFileList.Columns[1].HeaderCell.Value = "备份时间";
            //gvFileList.Columns[2].HeaderCell.Value = "文件大小";
            //gvFileList.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
        }

        private void btnRestore_Click(object sender, EventArgs e)
        {
            if (gvFileList.SelectedRows.Count > 0)
            {
                int index = gvFileList.SelectedRows[0].Index;
                string backupName = gvFileList.Rows[index].Cells[0].Value.ToString();
                string dbName = clbDbList.Text;

                DialogResult dr = MessageBox.Show("还原数据库会导致该节点后续\r\n数据丢失，是否仍然还原？", "提示", MessageBoxButtons.OKCancel);
                if (dr == DialogResult.OK)
                {
                    btnRestore.Enabled = false;
                    btnRestore.Text = "数据库还原中...";
                    clbDbList.Enabled = false;
                    Task task = new Task(() =>
                    { 
                        OneKeyRresore(dbName, backupName);
                        btnRestore.Enabled = true;
                        btnRestore.Text = "还原所选备份文件";
                        clbDbList.Enabled = true;
                    });
                    task.Start();
                }
            }
            else
            {
                MessageBox.Show("请先选择需要还原的数据库及相应备份文件！", "提示");
            }
        }

        /// <summary>
        /// 一键还原选中的数据库
        /// </summary>
        /// <param name="dbName"></param>
        /// <param name="backupPath"></param>
        private void OneKeyRresore(string dbName, string backupName)
        {
            string connStr = GetConnStr();
            if (SqlCommon.ConnectTest(connStr))
            {
                SqlCommand cmd = new SqlCommand();
                SqlConnection conn = new SqlConnection(connStr);
                string cmdText = @"restore database " + dbName + " from disk='" + FileCommon.backupPath + backupName + "' WITH REPLACE ";
                try
                {
                    conn.Open();
                    cmd.Connection = conn;
                    cmd.CommandType = CommandType.Text;
                    string setOffline = "Alter database " + dbName + " Set Offline With rollback immediate ";
                    string setOnline = " Alter database " + dbName + " Set Online With Rollback immediate";
                    cmd.CommandText = setOffline + cmdText + setOnline;
                    cmd.CommandTimeout = 300;
                    cmd.ExecuteNonQuery();
                    MessageBox.Show("恭喜你，数据成功恢复为所选文档的状态！", "系统消息");
                }
                catch (SqlException sexc)
                {
                    MessageBox.Show("操作失败，" + sexc.Message, "数据库错误消息");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("操作失败，" + ex.Message, "系统消息");
                }
                finally
                {
                    cmd.Dispose();
                    conn.Close();
                    conn.Dispose();
                }
            }
        }
    }
}
